//
//  DatabaseRongcloud.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/8.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "DatabaseRongcloud.h"

@implementation DatabaseRongcloud

+(instancetype)shareIntance{
    
    static DatabaseRongcloud *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        manager = [[DatabaseRongcloud alloc]init];
        
    });
    
    return manager;
}

+ (void)asynchronousPOSTWithURLString:(NSString *)urlString AppKey:(NSString *)appKey AppSecret:(NSString *)appSecret body:(NSData *)body PassBlock:(MyAsynchronousBlock)passBlock
{
    //获取一个随机标志
    NSString * nonce = [NSString stringWithFormat:@"%d",arc4random()];
    //获取时间戳
    NSString * timestamp = [[NSString alloc] initWithFormat:@"%ld",(long)[NSDate timeIntervalSinceReferenceDate]];
    //创建URL
    NSURL *url = [NSURL URLWithString:urlString];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求超时时间
    request.timeoutInterval = 10;
    
    //配置http header
    [request setValue:appKey forHTTPHeaderField:@"App-Key"];
    [request setValue:nonce forHTTPHeaderField:@"Nonce"];
    [request setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [request setValue:appSecret forHTTPHeaderField:@"appSecret"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //设置HTTPBody
    [request setHTTPBody:body];
    //设置请求方式
    [request setHTTPMethod:@"POST"];
    //创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    //创建数据处理的任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSData *da = data;
        dispatch_async(dispatch_get_main_queue(), ^{
            //利用passBlock传值
            passBlock(da);
        });
    }];
    [dataTask resume];
}

/**
 *  通过传入的字典来生成一个NSData数据
 *
 *  @param param 传入的字典对象
 *
 *  @return 需要的NSData对象
 */
+ (NSData *)httpBodyFromParamDictionary:(NSDictionary *)param
{
    NSMutableString * data = [NSMutableString string];
    for (NSString * key in param.allKeys) {
        [data appendFormat:@"%@=%@&",key,param[key]];
    }
    return [[data substringToIndex:data.length-1] dataUsingEncoding:NSUTF8StringEncoding];
}

/**
 *  用来获取token
 *
 *  @param block BLOCK
 */
- (void)getTokenWithBlock:(BLOCK)block
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.userID forKey:@"name"];
    [dic setValue:self.userID forKey:@"userId"];
    //取得当前用户的头像信息
    [dic setValue:@"http://www.deskcar.com/desktop/else/2012919110429/3.jpg" forKey:@"portraitUri"];
    NSData *da = [DatabaseRongcloud httpBodyFromParamDictionary:dic];
    [DatabaseRongcloud asynchronousPOSTWithURLString:@"https://api.cn.ronghub.com/user/getToken.json" AppKey:@"e5t4ouvptdysa" AppSecret:@"ERzQtKBm8D1n" body:da PassBlock:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
       
        block(dict[@"token"]);
    }];
    
}


@end
